package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.*;
import com.acme.bankapp.exceptions.bank.ClientsExistsException;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;

public class BankDataLoaderService {
    public static Bank loadBank(File file) throws IOException {
        Bank bank = new Bank();
        Scanner scanner = new Scanner(file);
        scanner.useDelimiter("\n");

        while (scanner.hasNext()) {
            String data = scanner.next();
            loadLine(bank, data);
        }



        return bank;
    }

    public static void loadLine(Bank bank, String line) {
        if (!Pattern.matches("^accounttype=(c|s);balance=([0-9])+;overdraft=([0-9])+;name=(.+);gender=(m|f);$", line)) {
            return;
        }
        Map<String, String> map = new HashMap<String, String>();
        for (String token : line.split(";")) {
            String[] elems = token.split("=");
            map.put(elems[0], elems[1]);
        }

        double balance = Double.parseDouble(map.get("balance"));
        double overdraft = Double.parseDouble(map.get("overdraft"));
        String name = map.get("name");
        Gender gender = map.get("gender").equals("m") ? Gender.MALE : Gender.FEMALE;

        Client client = new Client(name, gender);
        Account acc;
        if (map.get("accounttype").equals("s")) {
            acc = new SavingAccount(balance);
        } else {
            acc = new CheckingAccount(balance, overdraft);
        }
        client.addAccount(acc);
        try {
            bank.addClient(client);
        } catch (ClientsExistsException e) {
            //pass
        }
    }
}
